<template>
  <div class="publicpageview">
    <div class="publicformview">
      <el-form :inline="true" :model="listQuery" size="mini" ref="searchForm">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="区房屋管理单位：" prop="districtId">
              <CompanySelect v-model="listQuery.districtId" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="管理部(分中心)：" prop="houseAdminId">
              <DeptBrowser v-model="listQuery.houseAdminId" :queryDistrictId="listQuery.districtId" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="井盖类型：" prop="type">
              <el-select v-model="listQuery.type" placeholder="请选择" clearable>
                <el-option v-for="item in dictData.wellCoverTypeDict" :key="item.id" :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="具体位置：" prop="address">
              <el-input v-model="listQuery.address" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="整改措施：" prop="rectificationMeasures">
              <el-input v-model="listQuery.rectificationMeasures" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16" style="text-align: right;">
            <div>
              <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
              <el-button size="mini" @click="resetForm('searchForm')">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="publitableview">
      <el-button type="primary" size="mini" @click="handleAdd">新增</el-button>
      <el-button type="success" size="mini" @click="handleBatchImport">批量导入</el-button>
      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row size="mini">
        <el-table-column align="center" label="序号" type="index" width="60">
        </el-table-column>

        <el-table-column align="center" label="井盖编号" prop="coverNo" width="120">
        </el-table-column>

        <el-table-column align="center" label="井盖类型" prop="type" width="120">
          <template slot-scope="scope">
            {{ getDictName('wellCoverTypeDict', scope.row.type) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="区房屋管理单位" prop="districtName" width="160">
        </el-table-column>

        <el-table-column align="center" label="管理部(分中心)" prop="houseAdminName" width="140">
        </el-table-column>

        <el-table-column align="center" label="具体位置" prop="address" width="220">
        </el-table-column>

        <el-table-column align="center" label="隐患类型" prop="hiddenDangersType" width="120">
          <template slot-scope="scope">
            {{ getDictName('hiddenDangersTypeDict', scope.row.hiddenDangersType) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="治理前图片" prop="prePicCount" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.prePicCount > 0">
              <el-button type="text" size="mini" @click="handleViewImages(scope.row.prePic, '治理前图片')">
                查看({{ scope.row.prePicCount }})
              </el-button>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="治理后图片" prop="postPicCount" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.postPicCount > 0">
              <el-button type="text" size="mini" @click="handleViewImages(scope.row.postPic, '治理后图片')">
                查看({{ scope.row.postPicCount }})
              </el-button>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="备注" prop="note">
        </el-table-column>

        <el-table-column align="center" label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" size="mini" @click="handleView(scope.row)">详情</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="publicpaginationview">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.pageNum" background :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total" small>
        </el-pagination>
      </div>
    </div>

    <!-- 窨井盖治理弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" @close="handleDialogClose">
      <el-form :model="formData" :rules="formRules" ref="wellCoverForm" label-width="140px" size="small"
        class="safe-form">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="井盖编号：" prop="coverNo">
              <!-- <el-input v-model="formData.coverNo" v-if="!isReadonly" placeholder="请输入井盖编号"></el-input> -->
              <div v-if="!isReadonly" style="display: flex;">
                <el-input v-model="formData.coverNo" placeholder="请选择井盖编号" disabled></el-input>
                <el-button icon="el-icon-search" @click="handleSearchClick"></el-button>
              </div>
              <span v-else>{{ formData.coverNo }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="井盖类型：" prop="type">
              <!-- <el-select v-model="formData.type" v-if="!isReadonly" placeholder="请选择井盖类型" style="width: 100%">
                <el-option v-for="item in dictData.wellCoverTypeDict" :key="item.id" :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select> -->
              <span>{{ getDictName('wellCoverTypeDict', formData.type) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="区房屋管理单位：" prop="districtId">
              <CompanySelect v-model="formData.districtId" :display-label.sync="formData.districtName"
                :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="管理部(分中心)：" prop="houseAdminId">
              <DeptBrowser v-model="formData.houseAdminId" :display-label.sync="formData.houseAdminName"
                :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="具体位置：" prop="address">
              <!-- <el-input v-model="formData.address" v-if="!isReadonly" placeholder="请输入具体位置"></el-input> -->
              <span>{{ formData.address }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="隐患类型：" prop="hiddenDangersType">
              <el-select v-model="formData.hiddenDangersType" v-if="!isReadonly" placeholder="请选择隐患类型"
                style="width: 100%">
                <el-option v-for="item in dictData.hiddenDangersTypeDict" :key="item.id" :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
              <span v-else>{{ getDictName('hiddenDangersTypeDict', formData.hiddenDangersType) }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="隐患描述：" prop="hiddenDangersDecrip">
              <el-input v-model="formData.hiddenDangersDecrip" :disabled="isReadonly" type="textarea" :rows="3"
                placeholder="请输入隐患描述">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="整改措施：" prop="rectificationMeasures">
              <el-input v-model="formData.rectificationMeasures" :disabled="isReadonly" type="textarea" :rows="3"
                placeholder="请输入整改措施">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="治理状态：" prop="status">
              <el-select v-model="formData.status" v-if="!isReadonly" placeholder="请选择治理状态" style="width: 100%">
                <el-option v-for="item in dictData.treatmentStatusDict" :key="item.id" :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
              <span v-else>{{ getDictName('treatmentStatusDict', formData.status) }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="治理前图片：" prop="beforeImages">
              <ImageUpload v-model="formData.beforeImages" :max-count="5" :max-size="5"
                accept-types=".jpg,.jpeg,.png,.gif" :show-tips="true" :disabled="isReadonly" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="治理后图片：" prop="afterImages">
              <ImageUpload v-model="formData.afterImages" :max-count="5" :max-size="5"
                accept-types=".jpg,.jpeg,.png,.gif" :show-tips="true" :disabled="isReadonly" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注：" prop="note">
              <el-input v-model="formData.note" :disabled="isReadonly" type="textarea" :rows="3" placeholder="请输入备注信息">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ isReadonly ? '关 闭' : '取 消' }}</el-button>
        <el-button v-if="!isReadonly" type="primary" @click="handleSubmit" :loading="submitLoading">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入弹窗 -->
    <el-dialog title="上传文件" :visible.sync="uploadDialogVisible" width="900px" @close="handleUploadDialogClose">
      <div class="upload-container">
        <el-upload class="upload-dragger" drag :action="uploadAction" :file-list="fileList"
          :on-success="handleUploadSuccess" :on-error="handleUploadError" :on-change="handleFileChange"
          :before-upload="beforeUpload" :auto-upload="false" ref="upload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            请将文件拖动到此处，或<em>点击上传</em>
          </div>
        </el-upload>

        <div class="template-download">
          下载模板：<el-button type="text" @click="downloadTemplate">窨井盖治理模板</el-button>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleImport" :loading="importLoading">导 入</el-button>
      </div>
    </el-dialog>

    <!-- 图片列表查看弹窗 -->
    <el-dialog :title="imageListDialogTitle" :visible.sync="imageListDialogVisible" width="800px"
      @close="handleImageListDialogClose">
      <div class="image-list-view">
        <div v-for="(image, index) in currentImageList" :key="index" class="image-list-item">
          <img :src="image.url" @click="handlePreviewImage(image)" />
          <div class="image-info">
            <div class="image-name">{{ image.name }}</div>
            <div class="image-size">{{ formatFileSize(image.size) }}</div>
          </div>
        </div>
      </div>
      <div v-if="!currentImageList || currentImageList.length == 0" class="no-images">
        暂无图片
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="imageListDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog title="图片预览" :visible.sync="imagePreviewDialogVisible" width="800px"
      @close="handleImagePreviewDialogClose">
      <div class="image-preview-content">
        <img v-if="currentPreviewImage" :src="currentPreviewImage.url" alt="预览图片" />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="imagePreviewDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 选择井盖弹窗 -->
    <el-dialog title="井盖资料列表" :visible.sync="dialogFormVisible">
      <el-form :model="jgform" :inline="true">
        <el-form-item label="区房屋管理单位：" prop="districtId">
          <CompanySelect v-model="jgform.districtId" />
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getJgList"></el-button>

      </el-form>

      <el-table :data="jgData" border @row-click="handleRowClick">
        <el-table-column align="center" label="井盖编号" prop="coverNo" width="120">
        </el-table-column>

        <el-table-column align="center" label="井盖类型" prop="type" width="120">
          <template slot-scope="scope">
            {{ getDictName('wellCoverTypeDict', scope.row.type) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="区房屋管理单位" prop="districtName" width="160">
        </el-table-column>

        <el-table-column align="center" label="管理部(分中心)" prop="houseAdminName" width="140">
        </el-table-column>

        <el-table-column align="center" label="具体位置" prop="address" min-width="150">
        </el-table-column>
      </el-table>

      <div class="publicpaginationview" style="padding-bottom: 10px;">
        <el-pagination @size-change="handlejgSizeChange" @current-change="handlejgCurrentChange"
          :current-page="jgform.pageNum" background :page-sizes="[10, 20, 50, 100]" :page-size="jgform.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="jgtotal" small>
        </el-pagination>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { getCoverAdminList, getCoverAdminDetail, addCoverAdmin, updateCoverAdmin, deleteCoverAdmin } from '@/api/safe/yinjinggaiguanli/yinjinggaizhili'
import { getCoverInfoList } from '@/api/safe/yinjinggaiguanli/yinjinggaiziliao'
import { formatDate, formatDateTime } from '@/utils/dateUtils'
import { convertObjectIntegersToStrings, convertSpecificFieldsToStrings } from '@/utils/dataUtils'
import CompanySelect from "@/components/commonSelect/companySelect.vue";
import DeptBrowser from "@/components/SysBrowser/DeptBrowser.vue";
import ImageUpload from "@/components/ImageUpload.vue";

export default {
  name: 'YinjinggaiZhili',
  components: { DeptBrowser, CompanySelect, ImageUpload },

  data() {
    return {
      // 字典数据
      dictData: {
        // 井盖类型
        wellCoverTypeDict: [
          { id: '1', name: '街道井盖' },
          { id: '2', name: '小区井盖' },
          { id: '3', name: '管线井盖' },
          { id: '4', name: '排水井盖' }
        ],
        // 隐患类型
        hiddenDangersTypeDict: [
          { id: '1', name: '松动' },
          { id: '2', name: '破损' },
          { id: '3', name: '缺失' },
          { id: '4', name: '下沉' },
          { id: '5', name: '其他' }
        ],
        // 治理状态
        treatmentStatusDict: [
          { id: '1', name: '待治理' },
          { id: '2', name: '治理中' },
          { id: '3', name: '已完成' },
          { id: '4', name: '已验收' }
        ],
        // 区房屋管理单位
        districtDict: [
          { id: '1', name: '朝阳区房屋管理中心' },
          { id: '2', name: '海淀区房屋管理中心' },
          { id: '3', name: '西城区房屋管理中心' },
          { id: '4', name: '东城区房屋管理中心' }
        ],
        // 管理部
        houseAdminDict: [
          { id: '1', name: '朝阳管理部' },
          { id: '2', name: '海淀管理部' },
          { id: '3', name: '西城管理部' },
          { id: '4', name: '东城管理部' }
        ]
      },
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        districtId: "",
        houseAdminId: "",
        type: "",
        address: "",
        rectificationMeasures: ""
      },
      total: 0,
      jgData: [],
      dialogFormVisible: false,
      jgtotal: 0,
      list: [],
      listLoading: false,
      dialogVisible: false,
      uploadDialogVisible: false,
      imageListDialogVisible: false,
      imagePreviewDialogVisible: false,
      submitLoading: false,
      importLoading: false,
      dialogTitle: "新增窨井盖治理",
      imageListDialogTitle: "",
      isReadonly: false,
      currentEditId: null,
      currentImageList: [],
      currentPreviewImage: null,
      uploadAction: "/api/upload",
      fileList: [],
      formData: {
        id: null,
        adminId: 0,
        blockId: 0,
        coverNo: "",
        type: "",
        districtId: "",
        districtName: "",
        houseAdminId: "",
        houseAdminName: "",
        address: "",
        hiddenDangersType: "",
        hiddenDangersDecrip: "",
        rectificationMeasures: "",
        status: "",
        prePic: "",
        prePicCount: 0,
        postPic: "",
        postPicCount: 0,
        note: ""
      },
      formRules: {
        coverNo: [
          { required: true, message: '请输入井盖编号', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择井盖类型', trigger: 'change' }
        ],
        districtId: [
          { required: true, message: '请选择区房屋管理单位', trigger: 'change' }
        ],
        houseAdminId: [
          { required: true, message: '请选择管理部', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入具体位置', trigger: 'blur' }
        ],
        hiddenDangersType: [
          { required: true, message: '请选择隐患类型', trigger: 'change' }
        ],
        hiddenDangersDecrip: [
          { required: true, message: '请输入隐患描述', trigger: 'blur' }
        ],
        rectificationMeasures: [
          { required: true, message: '请输入整改措施', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择治理状态', trigger: 'change' }
        ]
      },
      jgform: {
        districtId: "",
        pageNum: 1,
        pageSize: 10
      }
    };
  },

  mounted() {
    this.getList();
    this.getJgList();
  },

  methods: {
    // 通用字典值改变处理
    handleDictChange(dictType, idField, nameField, value) {
      const item = this.dictData[dictType].find(item => item.id === value);
      this.formData[nameField] = item ? item.name : '';
    },

    // 区房屋管理单位选择改变
    onDistrictChange(value) {
      this.handleDictChange('districtDict', 'districtId', 'districtName', value);
    },

    // 管理部选择改变
    onHouseAdminChange(value) {
      this.handleDictChange('houseAdminDict', 'houseAdminId', 'houseAdminName', value);
    },

    // 通用字典名称查找方法
    getDictName(dictType, id) {
      const item = this.dictData[dictType].find(item => item.id === String(id));
      return item ? item.name : id;
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },

    handlejgSizeChange(val) {
      this.jgform.pageNum = 1;
      this.jgform.pageSize = val;
      this.getJgList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    handlejgCurrentChange(val) {
      this.jgform.pageNum = val;
      this.getJgList();
    },

    getJgList() {
      getCoverInfoList({ ...this.jgform }).then(res => {
        this.jgData = res.data.list;
        this.jgtotal = res.data.total
      })
    },

    // 获取列表数据
    getList() {
      this.listLoading = true;

      // 清理空值参数
      const params = {};
      Object.keys(this.listQuery).forEach(key => {
        if (this.listQuery[key] !== '' && this.listQuery[key] !== null) {
          params[key] = this.listQuery[key];
        }
      });

      getCoverAdminList(params).then(response => {
        this.listLoading = false;
        if (response.code == 200) {
          // 使用工具方法处理分页数据，将下拉框字段转为字符串
          const processedData = convertSpecificFieldsToStrings(response.data.list || [], ['type', 'districtId', 'houseAdminId', 'hiddenDangersType', 'status']);
          this.list = processedData;
          this.total = response.data.total || 0;
        } else {
          this.$message.error(response.message || '获取数据失败');
        }
      }).catch(() => {
        this.listLoading = false;
        this.$message.error('网络请求失败');
      });
    },

    // 搜索
    handleSearch() {
      this.listQuery.pageNum = 1;
      this.getList();
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getList();
    },

    // 新增
    handleAdd() {
      this.dialogTitle = "新增窨井盖治理";
      this.isReadonly = false;
      this.currentEditId = null;
      this.dialogVisible = true;
      this.resetFormData();
    },

    // 批量导入
    handleBatchImport() {
      this.uploadDialogVisible = true;
      this.fileList = [];
    },

    // 上传弹窗关闭
    handleUploadDialogClose() {
      this.fileList = [];
      this.$refs.upload.clearFiles();
    },

    // 下载模板
    downloadTemplate() {
      this.$message.success('模板下载中...');
    },

    // 上传前验证
    beforeUpload(file) {
      const isExcel = file.type == 'application/vnd.ms-excel' ||
        file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      if (!isExcel) {
        this.$message.error('只能上传 Excel 文件！');
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!');
        return false;
      }

      return true;
    },

    // 文件选择变化
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },

    // 上传成功
    handleUploadSuccess(response, file) {
      this.$message.success('文件上传成功');
    },

    // 上传失败
    handleUploadError(err, file) {
      this.$message.error('文件上传失败');
    },

    // 导入数据
    handleImport() {
      if (this.fileList.length == 0) {
        this.$message.warning('请先选择要导入的文件');
        return;
      }

      this.importLoading = true;
      setTimeout(() => {
        this.importLoading = false;
        this.uploadDialogVisible = false;
        this.$message.success('导入成功！');
        this.getList();
      }, 2000);
    },

    // 弹窗关闭
    handleDialogClose() {
      this.resetFormData();
      this.$refs.wellCoverForm.resetFields();
    },

    // 重置表单数据
    resetFormData() {
      this.formData = {
        id: null,
        adminId: 0,
        blockId: 0,
        coverNo: "",
        type: "",
        districtId: "",
        districtName: "",
        houseAdminId: "",
        houseAdminName: "",
        address: "",
        hiddenDangersType: "",
        hiddenDangersDecrip: "",
        rectificationMeasures: "",
        status: "",
        prePic: "",
        prePicCount: 0,
        postPic: "",
        postPicCount: 0,
        beforeImages: [], // 治理前图片数组
        afterImages: [],  // 治理后图片数组
        note: ""
      };
    },

    // 表单提交
    handleSubmit() {
      this.$refs.wellCoverForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;

          // 准备提交数据，新增时不传id
          const submitData = { ...this.formData };
          if (!this.currentEditId) {
            delete submitData.id;
          }

          // 处理图片数据：将数组转换为字符串
          submitData.prePic = JSON.stringify(this.formData.beforeImages || []);
          submitData.postPic = JSON.stringify(this.formData.afterImages || []);
          submitData.prePicCount = (this.formData.beforeImages || []).length;
          submitData.postPicCount = (this.formData.afterImages || []).length;

          // 判断是新增还是修改
          const apiCall = this.currentEditId ? updateCoverAdmin(submitData) : addCoverAdmin(submitData);

          apiCall.then(response => {
            this.submitLoading = false;
            if (response.code == 200) {
              this.dialogVisible = false;
              this.$message.success('操作成功！');
              this.getList();
            } else {
              this.$message.error(response.message || '操作失败');
            }
          }).catch(() => {
            this.submitLoading = false;
            this.$message.error('网络请求失败');
          });
        } else {
          this.$message.error('请填写完整信息');
          return false;
        }
      });
    },

    // 查看详情
    handleView(row) {
      this.dialogTitle = "查看窨井盖治理详情";
      this.isReadonly = true;
      this.currentEditId = row.id;

      getCoverAdminDetail(row.id).then(response => {
        if (response.code == 200) {
          // 使用工具方法处理详情数据，将下拉框字段转为字符串
          const processedData = convertSpecificFieldsToStrings(response.data, ['type', 'districtId', 'houseAdminId', 'hiddenDangersType', 'status']);

          // 处理图片数据：将字符串转换为数组
          processedData.beforeImages = this.parseImageString(processedData.prePic);
          processedData.afterImages = this.parseImageString(processedData.postPic);

          this.formData = { ...processedData };
          this.dialogVisible = true;
        } else {
          this.$message.error(response.message || '获取详情失败');
        }
      }).catch(() => {
        this.$message.error('网络请求失败');
      });
    },

    // 修改记录
    handleUpdate(row) {
      this.dialogTitle = "修改窨井盖治理";
      this.isReadonly = false;
      this.currentEditId = row.id;

      getCoverAdminDetail(row.id).then(response => {
        if (response.code == 200) {
          // 使用工具方法处理详情数据，将下拉框字段转为字符串
          const processedData = convertSpecificFieldsToStrings(response.data, ['type', 'districtId', 'houseAdminId', 'hiddenDangersType', 'status']);

          // 处理图片数据：将字符串转换为数组
          processedData.beforeImages = this.parseImageString(processedData.prePic);
          processedData.afterImages = this.parseImageString(processedData.postPic);

          this.formData = { ...processedData };
          this.dialogVisible = true;
        } else {
          this.$message.error(response.message || '获取详情失败');
        }
      }).catch(() => {
        this.$message.error('网络请求失败');
      });
    },



    // 删除记录
    handleDelete(id) {
      this.$confirm('此操作将删除该条内容，请确认是否继续操作？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCoverAdmin(id).then(response => {
          if (response.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          } else {
            this.$message.error(response.message || '删除失败');
          }
        }).catch(() => {
          this.$message.error('网络请求失败');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 图片相关方法
    // 查看图片列表
    handleViewImages(images, title) {
      this.currentImageList = JSON.parse(images);
      this.imageListDialogTitle = title;
      this.imageListDialogVisible = true;
    },

    // 图片列表弹窗关闭
    handleImageListDialogClose() {
      this.currentImageList = [];
      this.imageListDialogTitle = "";
    },

    // 预览单张图片
    handlePreviewImage(image) {
      this.currentPreviewImage = image;
      this.imagePreviewDialogVisible = true;
    },

    // 图片预览弹窗关闭
    handleImagePreviewDialogClose() {
      this.currentPreviewImage = null;
    },

    // 解析图片字符串为数组
    parseImageString(imageString) {
      if (!imageString) return [];
      try {
        const parsed = JSON.parse(imageString);
        return Array.isArray(parsed) ? parsed : [];
      } catch (error) {
        console.warn('解析图片字符串失败:', imageString, error);
        return [];
      }
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes == 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    handleSearchClick() {
      this.dialogFormVisible = true;
    },
    handleRowClick(row) {

      this.dialogFormVisible = false;
      this.formData.coverNo = row.coverNo;
      this.formData.type = row.type;
      this.formData.districtId = Number(row.districtId);
      this.formData.houseAdminId = row.houseAdminId;
      this.formData.address = row.address;
      this.formData.districtName = row.districtName;
      this.formData.houseAdminName = row.houseAdminName;
    }
  }
};
</script>

<style scoped>
/* 页面样式继承公共样式类 publicpageview, publicformview, publitableview */

/* 上传组件标准样式 */
.upload-container {
  padding: 20px 0;
  width: 100%;
}

.upload-dragger {
  width: 100% !important;
}

.upload-dragger .el-upload {
  width: 100% !important;
}

.upload-dragger .el-upload-dragger {
  width: 100% !important;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s ease;
  background-color: #fafafa;
  box-sizing: border-box;
}

.upload-dragger .el-upload-dragger:hover {
  border-color: #409EFF;
  width: 100%;
}

.upload-dragger .el-upload-dragger .el-icon-upload {
  font-size: 67px;
  color: #C0C4CC;
  margin: 40px 0 16px;
  line-height: 50px;
  width: 100%;
}

.upload-dragger .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.upload-dragger .el-upload__text em {
  color: #409EFF;
  font-style: normal;
}

.template-download {
  margin-top: 15px;
  font-size: 14px;
  color: #606266;
}

.template-download .el-button--text {
  color: #409EFF;
  padding: 0;
  font-size: 14px;
}

::v-deep .el-upload {
  width: 100% !important;
}

::v-deep .el-upload-dragger {
  width: 100% !important;
}

/* 图片上传和预览样式 */
.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 148px;
  height: 148px;
  display: inline-block;
  margin-right: 10px;
}

.image-uploader:hover {
  border-color: #409EFF;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  line-height: 1.4;
}

.uploaded-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.uploaded-image-item {
  position: relative;
  width: 148px;
  height: 148px;
  border: 1px solid #ddd;
  border-radius: 6px;
  overflow: hidden;
}

.uploaded-image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.uploaded-image-item:hover .image-actions {
  opacity: 1;
}

.image-actions {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-actions .el-button {
  color: #fff;
  border-color: #fff;
}

.image-preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-preview-item {
  width: 148px;
  text-align: center;
}

.image-preview-item img {
  width: 100%;
  height: 148px;
  object-fit: cover;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
}

.image-name {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  word-break: break-all;
}

.no-data {
  color: #999;
  font-size: 14px;
}

/* 图片列表查看弹窗样式 */
.image-list-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px 0;
  max-height: 400px;
  overflow-y: auto;
}

.image-list-item {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: box-shadow 0.3s;
}

.image-list-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-list-item img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  cursor: pointer;
}

.image-info {
  padding: 10px;
  background: #fafafa;
}

.image-size {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.no-images {
  text-align: center;
  color: #999;
  font-size: 14px;
  padding: 40px 0;
}

/* 图片预览弹窗样式 */
.image-preview-content {
  text-align: center;
  padding: 20px;
}

.image-preview-content img {
  max-width: 100%;
  max-height: 500px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>
